package com.example.waterdispenserm2.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.example.waterdispenserm2.adapter.M2Adapter;
import com.example.waterdispenserm2.adapter.M2HomeAdapter;
import com.example.waterdispenserm2.app.LPHYApplication;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.bean.M2UIItem;
import com.example.waterdispenserm2.databinding.ActivityM2Binding;
import com.example.waterdispenserm2.dp.M2NoodleHelperUtil;
import com.example.waterdispenserm2.inter.M2Interface;
import com.example.waterdispenserm2.inter.M2InterfaceUtil;
import com.example.waterdispenserm2.util.GetVideo;
import com.example.waterdispenserm2.vmc.DataParser;
import com.lake.banner.BannerConfig;
import com.lake.banner.ImageGravityType;
import com.lake.banner.VideoGravityType;
import com.lake.banner.loader.ViewItemBean;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class M2Activity extends BasicsActivity<ActivityM2Binding> implements M2Interface {
    M2HomeAdapter adapter;
    private final List<M2UIItem> jsonList=new ArrayList<>();
    private  final ArrayList<ViewItemBean> listViewItem = new ArrayList<ViewItemBean>();
    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initView() {
        M2InterfaceUtil.setM2Interface(this);
        GetVideo.getVideo();

        if (GetVideo.list != null && !GetVideo.list.isEmpty()) {
            listViewItem.clear();
            for (int i = 0; i < GetVideo.list.size(); i++) {
                int VideoTime = GetVideo.list.get(i).getVideoTime() * 1000;
                Uri path1 = Uri.parse(GetVideo.list.get(i).getPath());
                listViewItem.add(new ViewItemBean(BannerConfig.VIDEO, "", path1, VideoTime));
            }
        }
        if (!listViewItem.isEmpty()) {
            binding.banner.setViews(listViewItem)
                    .setCachePath(getExternalFilesDir(Environment.DIRECTORY_MOVIES).getAbsolutePath() + File.separator + "hbanner")
                    .setVideoGravity(VideoGravityType.FULL_SCREEN)//视频布局方式
                    .setImageGravity(ImageGravityType.FIT_XY)//图片布局方式
                    .setViewPagerIsScroll(false)//是否支持手滑
                    .start();
        }

        adapter=new M2HomeAdapter(jsonList,this);
        binding.lvData.setAdapter(adapter);
        binding.lvData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                jsonList.get(position).setSelect(!jsonList.get(position).isSelect());
                for (int i=0;i<jsonList.size();i++){
                    if (i!=position) {
                        jsonList.get(i).setSelect(false);
                    }
                }
                adapter.notifyDataSetChanged();

                if (!TextUtils.isEmpty(jsonList.get(position).getName())&&jsonList.get(position).isSelect()){
                    binding.ivAnimation.setVisibility(View.GONE);
                    binding.llText.setVisibility(View.VISIBLE);
                    binding.tvAmountWater.setText(jsonList.get(position).getAmountWater()+" ml");//水量
                    binding.tvHeatingDuration.setText(formatSecondsToMinutesAndSeconds(Integer.parseInt(jsonList.get(position).getHeatingDuration())));//时长
                    binding.tvWaterTemperature.setText(jsonList.get(position).getWaterTemperature()+"°C");//水温
                }else {
                    binding.ivAnimation.setVisibility(View.VISIBLE);
                    binding.llText.setVisibility(View.GONE);
                    binding.tvAmountWater.setText("");
                    binding.tvWaterTemperature.setText("");

                }
            }
        });

        binding.rlMu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(M2Activity.this, MoreActivity.class), 2);
            }
        });

        binding.rlAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String temp=  binding.tvWaterTemperature.getText().toString().trim();
                String volume=  binding.tvAmountWater.getText().toString().trim();
                if (LPHYApplication.bound) {
                    if (!TextUtils.isEmpty(temp)) {
                        if (!TextUtils.isEmpty(volume)) {
                            if ("0".equals(temp)) {//常温
                                LPHYApplication.serialService.sendWaterCommand(true, Integer.parseInt(temp), Integer.parseInt(volume), 1);
                            } else {//非常温
                                LPHYApplication.serialService.sendWaterCommand(true, Integer.parseInt(temp), Integer.parseInt(volume), 0);
                            }
                        }
                    }
                }else {
                    Toast.makeText(M2Activity.this,"上位机尚未与下位机连接",Toast.LENGTH_LONG).show();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            MainActivity.startActivity();
                        }
                    },2000);

                }
            }
        });

        binding.rlCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LPHYApplication.bound) {
                    LPHYApplication.serialService.sendWaterCommand(false, 0, 0,0);
                }else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            MainActivity.startActivity();
                        }
                    },2000);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        jsonList.clear();
        jsonList.addAll(M2NoodleHelperUtil.getInstance().getSQ());
        adapter.notifyDataSetChanged();


    }

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        System.out.println("------执行了onDestroy");
//        if (LPHYApplication.bound) {
//            unbindService(LPHYApplication.connection);
//            LPHYApplication.serialService.onDestroy();//关闭串口
//        }
//    }

    @Override
    protected ActivityM2Binding getViewBinding() {
        return ActivityM2Binding.inflate(LayoutInflater.from(this));
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            recreate();
        }
    }


    //总秒数转换成分秒
    @SuppressLint("DefaultLocale")
    public String formatSecondsToMinutesAndSeconds(int seconds) {
        int minutes = seconds / 60;
        int remainingSeconds = seconds % 60;
        return String.format("%02d:%02d", minutes, remainingSeconds);
    }

    //接收数据的变化
    @SuppressLint("SetTextI18n")
    @Override
    public void updateUI(DataParser.DeviceData data) {
        // 更新实时数据
        binding.tvCurrentTemp.setText(data.currentTemp + "℃");
        binding.tvCurrentVolume.setText(data.currentVolume + "ml");
    }
}